import axios from 'axios'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 10000 // request timeout
})

// Add a response interceptor
service.interceptors.response.use(res => {
  // 处理excel文件
  if (res.headers && (res.headers['content-type'] === 'application/octet-stream' || res.headers['content-type'] === 'application/x-msdownload' || res.headers['content-type'] === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
    var filename
    const disposition = res.headers['Content-Disposition']
    if (disposition && disposition.indexOf('attachment') !== -1) {
      var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
      var matches = filenameRegex.exec(disposition)
      if (matches != null && matches[1]) {
        filename = matches[1].replace(/['"]/g, '')
      }
    }
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', filename)

    document.body.appendChild(link)
    link.click()
  }
  return res
}, error => {
  // Do something with response error
  return Promise.reject(error.response.data || error.message)
})

export default service
